//package com.itheima.tlias84.interceptor;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.itheima.tlias84.dao.entity.Emp;
//import com.itheima.tlias84.dao.mapper.EmpMapper;
//import com.itheima.tlias84.utils.JwtUtil;
//import com.itheima.tlias84.utils.ResultUtil;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.util.Objects;
//
//@Slf4j
//@Component
//public class LoginInterceptor implements HandlerInterceptor {
//
//    @Resource
//    EmpMapper empMapper;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//
//        //("/login")路径在WebMvcConfig中被排除
//
//        log.info("拦截开始");
//
//        //获取请求头中的Token
//        String token = request.getHeader("token");
//        //判断是否有token
//        if (Objects.isNull(token)) {
//            writeErrorResp(response, "请先登录");
//            return false;
//        }
//        //判断token是否合法
//        try {
//            JSONObject object = JwtUtil.verifyToken(token);
//            Emp emp = empMapper.selectByUsername(object.getString("username"));
//            if (Objects.isNull(emp) || !emp.getPassword().equals(object.getString("password"))) {
//                writeErrorResp(response, "token不合法或已过期");
//                return false;
//            }
//        } catch (Exception e) {
//            writeErrorResp(response, "token不合法或已过期");
//            return false;
//        }
//
//        log.info("拦截完成");
//        return true;
//    }
//
//    private static void writeErrorResp(HttpServletResponse resp, String msg) throws IOException {
//        resp.setCharacterEncoding("UTF-8");
//        //设置响应状态码
//        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//
//        PrintWriter writer = resp.getWriter();
//        ResultUtil failure = ResultUtil.failure(msg);
//        writer.write(JSONObject.toJSONString(failure));
//    }
//}
